package nbcp.base.component


import com.fasterxml.jackson.annotation.JsonAutoDetect
import com.fasterxml.jackson.annotation.PropertyAccessor
import com.fasterxml.jackson.databind.JsonDeserializer
import com.fasterxml.jackson.databind.JsonSerializer
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.module.SimpleModule
import nbcp.base.extend.initObjectMapper


//@Component("DbJson")
class DbJsonMapper() : ObjectMapper()  {

    companion object {
        val INSTANCE: DbJsonMapper by lazy {
            return@lazy DbJsonMapper();
        }

        private val modules = mutableListOf<SimpleModule>()

        fun <T> registeObjectMapperTypeModule(type: Class<T>, ser: JsonSerializer<T>, deser: JsonDeserializer<T>) {
            var item = SimpleModule(type.name)
            item.addSerializer(type, ser)
            item.addDeserializer(type, deser);

            modules.removeAll { it.moduleName == type.name }

            modules.add(item);
        }
    }

    init {
        this.initObjectMapper();

        this.setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE);
        this.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE);
        this.setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE);
        this.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);

        modules.forEach {
            this.registerModule(it);
        }
    }
}

